﻿<!--
 * @Author: yubaolee <yubaolee@163.com> | ahfu~ <954478625@qq.com>
 * @Description: 代码生成器自动生成动态头部列表
 * @Copyright (c) 2022 by yubaolee | ahfu~ , All Rights Reserved. 
-->
<template>
  <div class="flex flex-column">
    <sticky>
      <el-input
        @keyup.enter="handleFilter"
        size="mini"
        style="width: 200px"
        class="filter-item"
        :placeholder="'名称'"
        v-model="listQuery.key"></el-input>
      <el-button
        class="filter-item"
        size="mini"
        icon="el-icon-search"
        @click="handleFilter">
        搜索
      </el-button>
      <permission-btn
        size="mini"
        v-on:btn-event="onBtnClicked"></permission-btn>
    </sticky>

    <auth-table
      ref="mainTable"
      :select-type="'checkbox'"
      :table-fields="headerList"
      :data="list"
      :v-loading="listLoading"
      @row-click="rowClick"
      @selection-change="handleSelectionChange"></auth-table>
    <el-pagination
      v-show="total > 0"
      :total="total"
      v-model:currentPage="listQuery.page"
      v-model:page-size="listQuery.limit"
      @current-change="handleCurrentChange" />
  </div>
  <el-dialog
    draggable
    class="dialog-mini"
    width="500px"
    :title="txtDlgTitle[dialogStatus]"
    v-model="dialogFormVisible">
    <auth-form
      ref="dataForm"
      :rules="rules"
      :edit-model="true"
      :form-fields="headerList"
      :data="temp"
      :col-num="2"></auth-form>
    <template v-slot:footer>
      <div>
        <el-button size="mini" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          size="mini"
          v-if="dialogStatus == 'create'"
          type="primary"
          @click="createData">
          确认
        </el-button>
        <el-button size="mini" v-else type="primary" @click="updateData">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
//引入核心框架
import { ElMessage, ElNotification } from 'element-plus'
import { onMounted, ref, reactive, nextTick } from 'vue'
//引入API，共用方法
import * as {TableName}s from '@/api/{TableName}s'
import { defaultVal } from '@/utils/index'
import { delrows } from '@/utils/delRows.js'
import ColumnDefine from '@/interface/columnDefine'
//引入组件
import Sticky from '@/components/Sticky/index.vue'
import permissionBtn from '@/components/PermissionBtn/index.vue'
import AuthForm from '../../components/Base/AuthForm.vue'
import AuthTable from '../../components/Base/AuthTable.vue'

const headerList = ref([]) //列表头
const multipleSelection = ref([]) //列表checkbox选中的值
const list = ref([]) //列表值
const total = ref(0) //总条数
const listLoading = ref(true) //进度条
const dialogFormVisible = ref(false) //是否显示编辑框
const dialogStatus = ref('')
let temp = reactive({}) //新增（编辑）绑定对话框

const listQuery = reactive({
  // 查询条件
  page: 1,
  limit: 20,
  key: undefined,
})

const txtDlgTitle = reactive({
  //对话框标题
  update: '编辑',
  create: '添加',
})
const rules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
})

//组件refs
const mainTable = ref(null)
const dataForm = ref(null)

onMounted(() => {
  headerList.value = [
     {HeaderList}
  ]
  getList()
})

const rowClick = function (row) {
  mainTable.value.clearSelection()
  mainTable.value.toggleRowSelection(row)
}
const handleSelectionChange = function (val) {
  multipleSelection.value = val
}
const onBtnClicked = function (domId, callback) {
  switch (domId) {
    case 'btnAdd':
      handleCreate()
      break
    case 'btnEdit':
      if (multipleSelection.value.length !== 1) {
        ElMessage.error({
          message: '只能选中一个进行编辑',
          type: 'error',
        })
        return
      }
      handleUpdate(multipleSelection.value[0])
      break
    case 'btnDel':
      if (multipleSelection.value.length < 1) {
        ElMessage.error({
          message: '至少删除一个',
          type: 'error',
        })
        return
      }
      handleDelete(multipleSelection)
      break
    case 'btnExport':
      mainTable.value.exportExcel('资源文件', callback)
      break
    default:
      break
  }
}
const getList = function () {
  listLoading.value = true
  {TableName}s.getList(listQuery).then(response => {
    list.value = response.data
    total.value = response.count
    listLoading.value = false
  })
}
const handleFilter = function () {
  listQuery.page = 1
  getList()
}
const handleSizeChange = function (val) {
  listQuery.limit = val
  getList()
}
const handleCurrentChange = function (val) {
  listQuery.page = val
  getList()
}
const handleModifyStatus = function (row, disable) {
  // 模拟修改状态
  ElMessage.success({
    message: '操作成功',
    type: 'success',
  })
  row.disable = disable
}
const resetTemp = function () {
  let obj = {}
  headerList.value.forEach(item => {
    obj[item.columnName] = defaultVal(item.entityType)
  })
  Object.assign(temp, obj)
}
const handleCreate = async function () {
  // 弹出添加框
  resetTemp()
  dialogStatus.value = 'create'
  dialogFormVisible.value = true
  await nextTick()
  dataForm.value.clearValidate()
}
const createData = function () {
  // 保存提交
  dataForm.value.validate(() => {
    {TableName}s.add(temp).then(() => {
      list.value.unshift(temp)
      dialogFormVisible.value = false
      ElNotification({
        title: '成功',
        message: '创建成功',
        type: 'success',
        duration: 2000,
      })
    })
  })
}
const handleUpdate = async function (row) {
  // 弹出编辑框
  Object.assign(temp, row) //必需这样赋值才能响应式
  dialogStatus.value = 'update'
  dialogFormVisible.value = true
  await nextTick()
  dataForm.value.clearValidate()
}
const updateData = function () {
  // 更新提交
  dataForm.value.validate(() => {
    const tempData = Object.assign({}, temp)
    {TableName}s.update(tempData).then(() => {
      for (const v of list.value) {
        if (v.id === temp.id) {
          const index = list.value.indexOf(v)
          list.value.splice(index, 1, temp)
          break
        }
      }
      dialogFormVisible.value = false
      ElNotification({
        title: '成功',
        message: '更新成功',
        type: 'success',
        duration: 2000,
      })
    })
  })
}
const handleDelete = function (rows) {
  // 多行删除
  delrows({TableName}s, rows)
}
</script>
